
import { sendEmail } from "@/api/login"
import { Button, Form, message, Input } from 'antd';
import { Statistic } from 'antd';
import { useState } from "react";
const { Countdown } = Statistic;

/**
 * @description 邮箱
 */
function EmailForm({ form, tableName, showLabel = true }) {
  const [isCount, setIsCount] = useState(false)
  let deadline = Date.now() + 1000 * 60; // Dayjs is also OK
  // 发送验证码
  let sendemailcode = async () => {
    try {
      // [1] 校检邮箱是否正确
      let res = await form.validateFields(['email'])

      // [2] 后端请求发送验证码
      await sendEmail(tableName, res.email)

      // [3] 按钮变化 + 倒计时
      setIsCount(true)
      deadline = Date.now() + 1000 * 60

      message.success('发送成功')
    } catch (error) {

      message.error('发送失败')
      console.error(error)
    }

  }

  // 倒计时结束
  let handleCountEnd = () => {
    setIsCount(false)
  }
  return (
    <>
      <Form.Item
        label={showLabel ? '邮箱' : null}
      >

        <div className='email-wrapper'>
          <Form.Item
            name='email'
            noStyle
            rules={[
              {
                required: true,
                message: '请输入邮箱'
              },
              {
                pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/,
                message: '请输入正确的邮箱'
              }
            ]}
          >
            <Input className="email-input" placeholder='邮箱' allowClear />
          </Form.Item>

          <Button onClick={sendemailcode} className='email-btn' disabled={isCount}>
            {
              isCount ?
                <Countdown value={deadline} format="ss秒后重发" onFinish={handleCountEnd} />
                :
                '发送验证码'
            }
          </Button>

        </div>

      </Form.Item>

      <Form.Item
        label={showLabel ? '验证码' : null}
        name='emailcode'
        rules={[{
          required: true,
          message: '请输入验证码'
        }]}

      >
        <Input className="email-code-input" placeholder='输入验证码' allowClear />
      </Form.Item></>
  )
}

export default EmailForm